package eu.flatworld.android.ontop;

import java.util.List;

import android.app.Activity;
import android.app.Dialog;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Adapter;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockListFragment;
import com.actionbarsherlock.view.MenuItem;
import com.j256.ormlite.android.apptools.OpenHelperManager;

import eu.flatworld.android.ontop.db.DatabaseHelper;
import eu.flatworld.android.ontop.db.Memo;
import eu.flatworld.android.ontop.db.Util;

public class MemoListFragment extends SherlockListFragment {
	private DatabaseHelper dbh = null;

	private Callbacks mCallbacks = sDummyCallbacks;

	public interface Callbacks {
		/**
		 * Callback for when an item has been selected.
		 */
		public void onMemoSelected(Memo m);
	}

	private static Callbacks sDummyCallbacks = new Callbacks() {
		@Override
		public void onMemoSelected(Memo m) {
		}
	};

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);

		// Activities containing this fragment must implement its callbacks.
		if (!(activity instanceof Callbacks)) {
			throw new IllegalStateException(
					"Activity must implement fragment's callbacks.");
		}

		mCallbacks = (Callbacks) activity;
	}

	@Override
	public void onDetach() {
		super.onDetach();
		// Reset the active callbacks interface to the dummy implementation.
		mCallbacks = sDummyCallbacks;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		Log.d(Main.LOGTAG, "create memolistfragment");
		super.onCreate(savedInstanceState);
	}

	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		super.onViewCreated(view, savedInstanceState);
		ActionBar bar = getSherlockActivity().getSupportActionBar();
		bar.setSubtitle(R.string.available_lists);
		registerForContextMenu(this.getListView());
		setHasOptionsMenu(true);
		loadMemoList();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();

		if (dbh != null) {
			OpenHelperManager.releaseHelper();
			dbh = null;
		}
	}

	@Override
	public void onResume() {
		super.onResume();
	}

	Memo createMemo(String name) {
		try {
			return Util.createMemo(getDbHelper(), name);
		} catch (java.sql.SQLException ex) {
			String s = getString(R.string.error_creating_the_list);
			Toast.makeText(getActivity(), s, Toast.LENGTH_LONG).show();
			Log.e(Main.LOGTAG, s, ex);
		}
		return null;
	}

	void deleteMemo(Memo m) {
		try {
			Util.deleteChecklistItems(getDbHelper(), m);
			Util.deleteMemo(getDbHelper(), m);
		} catch (java.sql.SQLException ex) {
			String s = getString(R.string.error_creating_the_list);
			Toast.makeText(getActivity(), s, Toast.LENGTH_LONG).show();
			Log.e(Main.LOGTAG, s, ex);
		}
	}

	void loadMemoList() {
		try {
			List<Memo> lm = Util.loadMemoList(getDbHelper());
			ArrayAdapter<Memo> adapter = new ArrayAdapter<Memo>(getActivity(),
					android.R.layout.simple_list_item_1, lm);
			setListAdapter(adapter);
		} catch (java.sql.SQLException ex) {
			String s = getString(R.string.error_loading_the_lists);
			Toast.makeText(getActivity(), s, Toast.LENGTH_LONG).show();
			Log.e(Main.LOGTAG, s, ex);
		}
	}

	private DatabaseHelper getDbHelper() {
		if (dbh == null) {
			dbh = OpenHelperManager.getHelper(getActivity(),
					DatabaseHelper.class);
		}
		return dbh;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// This uses the imported MenuItem from ActionBarSherlock
		if (item.getItemId() == OnTopActivity.MENU_ADD_ID) {
			Dialog dialog = new Dialog(getActivity());
			dialog.setTitle(R.string.enter_list_name_);
			dialog.setContentView(R.layout.createlistdialog);
			final Button b = (Button) dialog.findViewById(R.id.bOk);
			b.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					String value = b.getText().toString();
					if (value.trim().length() == 0) {
						value = getString(R.string.no_name);
					}
					Memo m = createMemo(value);
					loadMemoList();
					return;
				}
			});
			final Button b2 = (Button) dialog.findViewById(R.id.bCancel);
			b2.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					return;
				}
			});
			dialog.show();
			return true;
		}

		// Toast.makeText(this, "Got click: " +
		// item.toString(),Toast.LENGTH_SHORT).show();
		return true;
	}

	@Override
	public void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);

		Memo m = (Memo) getListAdapter().getItem(position);
		mCallbacks.onMemoSelected(m);
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);

		menu.clear();
		// menu.setHeaderIcon(R.drawable.icon);
		// menu.setHeaderTitle(R.string.options);

		AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
		int position = info.position;
		Adapter adapter = ((ListView) v).getAdapter();
		Memo m = (Memo) adapter.getItem(position);
		menu.setHeaderTitle(m.getName());
		menu.add(R.string.delete);
	}

	@Override
	public boolean onContextItemSelected(android.view.MenuItem item) {
		AdapterContextMenuInfo info = (AdapterContextMenuInfo) item
				.getMenuInfo();
		Memo m = (Memo) getListAdapter().getItem(info.position);
		deleteMemo(m);
		loadMemoList();
		return true;
	}
}